package com.sm.healthy.ui.fragment

import android.os.Bundle
import androidx.fragment.app.Fragment
import com.sm.healthy.R
import com.sm.healthy.base.BaseFragment
import com.sm.healthy.base.handle.TopHandle
import com.sm.healthy.databinding.FragmentEcgMeasurementBinding
import com.sm.healthy.device.MedicalProtocol
import com.sm.healthy.device.interfaces.Up_ECGListener
import com.sm.healthy.event.SerialPortDataMsgEvent
import com.sm.healthy.model.EcgMeasurementViewModel
import com.sm.healthy.ui.view.ecg.WaveInfo
import com.sm.healthy.utils.DataUtils
import com.sm.healthy.utils.SerialPortUtil
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*


/**
 * A simple [Fragment] subclass.
 * Use the [EcgMeasurementFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class EcgMeasurementFragment :
    BaseFragment<EcgMeasurementViewModel, FragmentEcgMeasurementBinding>(), Up_ECGListener {

    private var isPause = true
    private var isLeadOff = true //导联是否脱落
    private var isDeviceOff = true

    private val heartRates by lazy {
        arrayListOf<Int>()
    }
    private val medicalProtocol by lazy(LazyThreadSafetyMode.NONE) {
        MedicalProtocol()
    }

    override fun layoutId(): Int {
        return R.layout.fragment_ecg_measurement
    }

    override fun initView(savedInstanceState: Bundle?) {
        EventBus.getDefault().register(this)
        mDatabind.handle = TopHandle(nav())
        mDatabind.click = Click()
        mDatabind.model = mViewModel
        mDatabind.backLayout.post {
            mDatabind.backLayout.startDraw()
            mDatabind.layoutWave.initStyle()
            WaveInfo.getInstance().init(mDatabind.backLayout)
            WaveInfo.getInstance().setLayout(WaveInfo.WaveLayout.LAYOUT_12x1)
            medicalProtocol.setUp_ecgListener(this)
        }
    }

    /**
     * 改变导联状态
     *
     * @param isOff 是否导联脱落
     */
    private fun onLeadStatusChange(isOff: Boolean) {
        isPause = isOff
        isLeadOff = isOff
    }


    /**
     * 改变设备状态
     *
     * @param isOff 设备是否断开
     */
    private fun onDeviceStatusChange(isOff: Boolean) {
        isPause = isOff
        isDeviceOff = isOff
        if (isOff) {
//            cancelTheAcion()
            //            actHeratRateCountDownBtn.onCancel();
        }
//        if (actHeratRateCountDownBtn.isEnabled()) {
//            actHeratRateCountDownBtn.setEnabled(!isOff)
//        } else {
//            if (!isLeadOff) actHeratRateCountDownBtn.setEnabled(!isOff) else {
//            Toast.makeText(mContext, R.string.lead_off, Toast.LENGTH_SHORT).show();
//            }
//        }
    }


    override fun onDestroyView() {
        super.onDestroyView()
        medicalProtocol.setUp_ecgListener(null)
        EventBus.getDefault().unregister(this)
    }

    var isStart = true

    inner class Click {
        fun startMeasurement() {
            if (isStart) {
                startMeasure()
                mViewModel.startBtn.set("停止测量")
                mDatabind.textView4.setBackgroundResource(R.drawable.bg_btn_red_shape)
            } else {
                stopMeasure()
                mViewModel.startBtn.set("开始测量")
                mDatabind.textView4.setBackgroundResource(R.drawable.bg_btn_blue_shape)
            }
            isStart = !isStart
        }

        fun goHistory() {
            if (isStart) return mViewModel.toast.postValue("请先停止测量")
            nav().navigateAction(R.id.historyDataFragment)
        }
    }

    /**
     * 开始测量
     */
    private fun startMeasure() {

    }

    private fun stopMeasure() {
        if (heartRates.size < 3) return mViewModel.toast.postValue("数据过少，保存失败！")
        dealData()

    }

    private fun dealData() {

        //去掉一个最大值和最小值
        heartRates.remove(Collections.max(heartRates))
        heartRates.remove(Collections.min(heartRates))

        val heartRateAve: Int = DataUtils.getAve(heartRates)
        mViewModel.ecgEntity.value?.heartRate = heartRateAve
        mViewModel.insert()
        heartRates.clear()
    }

    override fun onECG_Wave(wave: Int, heartbeat: Boolean) {
        if (isDeviceOff) onDeviceStatusChange(false)
        if (isStart.not()) return
        mDatabind.layoutWave.length(wave - 2048)
    }

    override fun onECG_Lead_STS(status: Byte) {
    }

    override fun onECG_HeartRate(rate: Int) {
        if (isStart.not()) return
        if (rate > 300 || rate < 15) {
            mViewModel.ecgValue.set("---")
        } else {
            mViewModel.ecgValue.set(rate.toString())
            heartRates.add(rate)
        }
        when {
            rate <= 60 -> {
                mViewModel.ecgEntity.value?.levelPul = 1
                mDatabind.tvLevel.changeLevel(1)
            }
            rate in 61..99 -> {
                mViewModel.ecgEntity.value?.levelPul = 0
                mDatabind.tvLevel.changeLevel(0)
            }
            rate >= 100 -> {
                mViewModel.ecgEntity.value?.levelPul = 2
                mDatabind.tvLevel.changeLevel(2)
            }
        }

//        mViewModel.insert()
    }

    override fun onECG_HeartRateStatus(status: String?) {
    }


    @Subscribe(threadMode = ThreadMode.POSTING)
    fun onGetMsg(serialPortDataMsgEvent: SerialPortDataMsgEvent) {
        when (serialPortDataMsgEvent.action) {
            SerialPortUtil.ACTION_SERIAPORT_READ -> {
                val data: ByteArray = serialPortDataMsgEvent.data
                val size: Int = serialPortDataMsgEvent.size
                medicalProtocol.Resolve(data, 0, size)
            }
        }
    }

}